package com.jgp.security.shiro.config;

import com.jgp.security.shiro.exception.SecurityException;
import com.jgp.sys.ui.Result;
import com.jgp.sys.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019/1/2
 */
@Order(400)
@Slf4j
@ControllerAdvice
@Configuration
public class GlobalSecurityExceptionConfiguration {
    
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = SecurityException.class)
    @ResponseBody
    public ModelAndView resolveException(HttpServletRequest request, Exception ex) {
        SecurityException jgpException = (SecurityException) ex;
        ex.printStackTrace();
        //logger.error(re.getPrefix()+"【"+re.getCode()+"】:"+re.getMsg(),re);
        ModelAndView mav;
        Result result = new Result();
        result.flag(false).error(jgpException.getCode(), jgpException.getMessage(), jgpException.getModule());
        if (HttpUtil.isAjax(request)) {
            mav = new ModelAndView(new MappingJackson2JsonView());
            mav.addObject(result);
        } else {
            mav = new ModelAndView("/back/error");
            mav.addObject("error", result.getErrors());
        }
        return mav;
    }
    
}
